<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>商品信息</title>
</head>
<body>
<h1>JSP数据库实例&nbsp;&nbsp;<%=(new java.util.Date()).toLocaleString()%></h1>
<% out.println("Your IP address is " + request.getRemoteAddr());%>

<%-- 该部分注释在网页中不会被显示--%>
<table border="1" width="100%">
    <tr>
        <th>ID</th>
        <th>商品名称</th>
        <th>分类ID</th>
        <th>类型ID</th>
    </tr>
    <%
        try {
            String driver = "com.mysql.jdbc.Driver";
            String db_url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8"; //数据库名?后面的是为了指定字符的编码.解码格式。
            String username = "root";  //数据库用户名
            String password = "root";  //数据库用户密码

            Statement stmt = null;
            String sql = null;
            Connection conn = null;

            // 注册 JDBC 驱动
            Class.forName(driver);

            // 打开链接
            //out.println("连接数据库...");
            conn = DriverManager.getConnection(db_url, username, password);
            if (conn != null) {
                stmt = conn.createStatement();//实例化Statement对象(获取一个可以执行sql语句的对象)
                sql = "select * from goods";
                ResultSet rs = stmt.executeQuery(sql);
                // 展开结果集数据库
                while (rs.next()) {
                    // 通过字段检索
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
                    Short class_id = rs.getShort("type_id");
                    Short type_id = rs.getShort("type_id");
    %>


    <tr>
        <td><%=id %></td>
        <td><%=name %></td>
        <td><%=class_id %></td>
        <td><%=type_id %></td>
    </tr>

    <%
                }

            } else {
                out.println("连接失败");
            }

        } catch (SQLException se) {
            // 处理 JDBC 错误
            //se.printStackTrace();
            out.println("连接失败");
        } catch (Exception e) {
            // 处理 Class.forName 错误
            //e.printStackTrace();
            out.println("连接失败");
        }

    %>
</table>


<jsp:useBean id="student" class="com.data.bean.StudentsBean">
    <jsp:setProperty name="student" property="name"
                     value="小强"/>
    <jsp:setProperty name="student" property="age"
                     value="10"/>
</jsp:useBean>

<p>学生名字:
    <jsp:getProperty name="student" property="name"/>
</p>

<p>学生年龄:
    <jsp:getProperty name="student" property="age"/>
</p>

<%
    //response.sendError(404, "Need authentication!!!" );
%>

</body>
</html>
